import avatar from '@/img/botAvatar.png';
import request from '@/utils/request';
import { Avatar, Button, Input, Toast } from 'antd-mobile';
import { LocationOutline, SetOutline } from 'antd-mobile-icons';
import { LoaderIcon } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { Helmet } from 'umi';
import styles from './index.less';

import {
  vscDarkPlus,
  coyWithoutShadows,
} from 'react-syntax-highlighter/dist/esm/styles/prism'; // 代码高亮主题风格
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import classNames from 'classnames';
import Markdown from 'markdown-to-jsx';
const them = {
  dark: vscDarkPlus,
  light: coyWithoutShadows,
};


const markdownContent = `
# 示例文档

这是一个包含多种 Markdown 语法的示例文档。

## 段落

Markdown 是一种轻量级的标记语言，允许你使用简单的语法来格式化文本。

## 列表

### 无序列表

- 项目 1
- 项目 2
  - 子项目 2.1
  - 子项目 2.2
- 项目 3

### 有序列表

1. 第一项
2. 第二项
3. 第三项

## 代码块

下面是一个 JavaScript 代码示例：

\`\`\`javascript
function greet(name) {
  return \`Hello, \${name}!\`;
}
\`\`\`

## 表格

| 姓名     | 年龄 | 城市         |
|----------|------|--------------|
| Alice    | 30   | New York     |
| Bob      | 25   | Los Angeles  |
| Charlie  | 35   | Chicago      |

## 链接

[访问 OpenAI](https://www.openai.com)

## 图片

![示例图片](https://via.placeholder.com/150 "示例图片")
`;


// 计算单双数
var isEven = number => {
  return number % 2 === 0;
};

const generateUniqueID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = (Math.random() * 16) | 0;
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export default props => {
  const [messages, setMessages] = useState([]);
  const [inputText, setInputText] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isDarkTheme, setIsDarkTheme] = useState(true);
  const [isWaiting, setIsWaiting] = useState(false);
  const messagesEndRef = useRef(null);
  const contentTextRef = useRef('');

  useEffect(() => {
    const fetchInitialMessages = async () => {
      try {
        setIsLoading(true);
        const response = await request('/api/test/welcome');
        const { data = {} } = response;
        setMessages([
          {
            id: generateUniqueID(),
            text: data.welcome_msg,
            think: '',
            type: 'bot',
          },
        ]);
      } catch (error) {
        console.error('Error fetching initial messages:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchInitialMessages();
  }, []);

  // const scrollToBottom = () => {
  //   messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  // };

  // useEffect(() => {
  //   scrollToBottom();
  // }, [messages]);

  useEffect(() => {
    document.documentElement.setAttribute(
      'data-theme',
      isDarkTheme ? 'dark' : 'light',
    );
  }, [isDarkTheme]);

  const handleSend = async () => {
    if (!inputText.trim() || isLoading) return;

    // Add user message
    const userMessageId = generateUniqueID();
    setMessages(prev => [
      ...prev,
      { id: userMessageId, text: inputText, type: 'user' },
    ]);
    setIsWaiting(true);
    setIsLoading(true);

    setInputText('');
    try {
      var url = `${process.env.apiUrl}/api/test/chat`;
      const conversation_id = Math.floor(Math.random() * 900000) + 100000;
      let response = await window.fetch(url, {
        mode: 'cors',
        credentials: 'omit',
        method: 'POST',
        body: JSON.stringify({
          query: inputText,
          conversation_id,
        }),
        headers: {
          'Content-Type': 'application/json',
          Accept: 'text/event-stream',
        },
      });
      if ((response || {}).status === 200) {
        contentTextRef.current = '';
        // 获取UTF8的解码
        const encode = new TextDecoder('utf-8');

        // 获取body的reader
        const reader = response.body.getReader();
        let shouldContinue = true;

        let currentReasoningContent = '';
        let newMessageInserted = false; // 标记是否已经插入新消息
        let botMessageId = generateUniqueID();

        // 循环读取reponse中的内容
        while (shouldContinue) {
          const { done, value } = await reader.read();

          if (done) {
            console.log('结束了');
            setIsLoading(false);
            setIsWaiting(false);
            break;
          }
          // 解码内容
          const lines = encode
            .decode(value)
            .replace(/\r/g, '')
            .split('\n')
            .filter(line => line.trim() !== '');

          for (const item of lines) {
            if (item.includes('data: Error: ')) {
              shouldContinue = false;
              Toast.show({
                content: '获取内容失败',
                duration: 5000,
              });
              setMessages(prev => {
                const newMessages = prev.map(msg => {
                  if (msg.id === botMessageId) {
                    return { ...msg, isThinking: false };
                  }
                  return msg;
                });
                return newMessages;
              });
              setIsLoading(false);
              setIsWaiting(false);
              return;
            }

            const matchResult = item.match(/{.*}/);
            if (matchResult) {
              try {
                const obj = JSON.parse(matchResult[0]);
                console.log(obj);
                if (obj.reasoning_content && !newMessageInserted) {
                  setMessages(prev => [
                    ...prev,
                    {
                      id: botMessageId,
                      think: obj.reasoning_content,
                      type: 'bot',
                      isThinking: true,
                    },
                  ]);
                  currentReasoningContent = obj.reasoning_content;
                  newMessageInserted = true;
                  setIsWaiting(false);
                } else if (obj.reasoning_content) {
                  currentReasoningContent += obj.reasoning_content;
                  setMessages(prev => {
                    const newMessages = prev.map(msg => {
                      if (msg.id === botMessageId) {
                        return { ...msg, think: currentReasoningContent };
                      }
                      return msg;
                    });
                    return newMessages;
                  });
                }

                if (obj.content) {
                  contentTextRef.current += obj.content;
                  setMessages(prev => {
                    const newMessages = prev.map(msg => {
                      if (msg.id === botMessageId) {
                        return {
                          ...msg,
                          text: (msg.text || '') + obj.content,
                        };
                      }
                      return msg;
                    });
                    return newMessages;
                  });
                }

                if (obj.finish_reason === 'stop') {
                  const characters = contentTextRef.current.split('');
                  let currentIndex = 0;

                  const displayNextCharacter = () => {
                    if (currentIndex < characters.length) {
                      setMessages(prev => {
                        const newMessages = prev.map(msg => {
                          if (msg.id === botMessageId) {
                            return {
                              ...msg,
                              text: (msg.text || '') + characters[currentIndex],
                              isThinking: false,
                            };
                          }
                          return msg;
                        });
                        return newMessages;
                      });
                      currentIndex++;
                      requestAnimationFrame(displayNextCharacter);
                    } else {
                      setIsLoading(false);
                    }
                  };

                  displayNextCharacter();
                  contentTextRef.current = '';
                }
              } catch (error) {
                setIsWaiting(false);
                console.error('JSON 解析错误:', error);
              }
            }
          }
        }
      } else {
        Toast.show({
          content: '获取内容失败',
        });
        setIsLoading(false);
        setIsWaiting(false);
      }
    } catch (error) {
      setIsLoading(false);
      setIsWaiting(false);
    }
  };

  const toggleTheme = () => {
    setIsDarkTheme(prev => !prev);
  };

  //获取展示内容
  var getShowText = (textStr = '') => {

    // 代码段截取符号
    const char = '```';
    // 存放代码段符号下标的数组
    const positions = [0];
    // 获取代码段符号位置
    let pos = textStr.indexOf(char);
    while (pos !== -1) {
      positions.push(pos);
      pos = textStr.indexOf(char, pos + 1);
    }
    const arr = [];
    // 根据代码段符号下标获取代码段
    for (let i = 0; i < positions.length; i++) {
      if (!isEven(i + 1)) {
        const str =
          positions?.length > i + 1
            ? textStr
                .substring(positions[i], positions[i + 1])
                .replace('```', '')
            : textStr.substring(positions[i]).replace('```', '');
        arr.push({
          type: 2,
          num: positions[i],
          message: str,
        });
      }
      if (!isEven(i)) {
        const str = textStr
          .substring(positions[i], positions[i + 1])
          .replace('```', '');
        arr.push({
          type: 1,
          num: positions[i],
          message: str,
        });
      }
    }
    
    var isUser = false

    return (
      <div
        className={classNames([
          styles.chatrow,
          {
            [styles.chatrowUser]: isUser,
          },
        ])}
      >
        <div className={styles.chatWrap}>
         
          <div className={styles.chatContent}>
            {/* {arr.map(it => {
              // 获取第一个回车符的下标
              const nindex = it.message.indexOf('\n');
              // 代码类型
              const codeType =
                it.type == 1 ? it.message.substring(0, nindex) : false;
              // 代码输出
              const codeMessage =
                it.type == 1 && nindex !== -1
                  ? it.message.substring(nindex)
                  : it.message;

              console.log(codeMessage,3333);

              return it.type == 1 ? (
                <>
                  <CopyToClipboard
                    onCopy={() => {
                      // Messages.success('复制成功');
                    }}
                    text={codeMessage}
                  >
                    <div className={styles.copyCode}>Copy code</div>
                  </CopyToClipboard>
                  <SyntaxHighlighter
                    showLineNumbers={false} // 是否展示左侧行数
                    lineNumberStyle={{ color: '#ddd', fontSize: 10 }} // 左侧行数的样式
                    style={them.dark} // 主题风格
                    language={codeType || 'javascript'} // 需要语言类型 如css, jsx , javascript 等
                    PreTag="div"
                  >
                    {String(codeMessage).replace(/\n$/, '')}
                  </SyntaxHighlighter>
                </>
              ) : (
                it.message.split('/n').map(item => {
                  return (
                    <ReactMarkdown>
                      {item}
                    </ReactMarkdown>
                  );
                })
              );
            })} */}
            <Markdown>
              {textStr}
            </Markdown>
          </div>
        </div>
      </div>
    );
  };


  
  return (
    <div className={styles.pageRoot}>
      <Helmet>
        <title>AI助手</title>
      </Helmet>

      <div className={styles.chatContainer}>
        <div className={styles.header}>
          <span className={styles.title}>AI助手</span>
          <Button
            className={styles.themeToggle}
            onClick={toggleTheme}
            fill="none"
          >
            <SetOutline className={styles.themeIcon} />
            <span className={styles.themeText}>
              {isDarkTheme ? '浅色' : '深色'}
            </span>
          </Button>
        </div>

        <div className={styles.messageList}>
          {/* <Markdown>{markdownContent}</Markdown> */}
          {messages.map((message, index) => (
            <div
              key={index}
              className={`${styles.messageItem} ${
                message.type === 'user' ? styles.userMessage : styles.botMessage
              }`}
            >
              {message.type === 'bot' && (
                <>
                  <Avatar
                    src={avatar}
                    className={styles.avatar}
                    alt="bot avatar"
                  />
                  <div className={styles.messageContent}>
                    {message.think && (
                      <div className={styles.messageThink}>
                        {getShowText(message.think)}
                      </div>
                    )}
                    {message.isThinking && (
                      <div className={styles.generateTip}>
                        <LoaderIcon className={styles.animateSpin} />
                        <span>Thinking ...</span>
                      </div>
                    )}
                    <div className={styles.messageText}>
                       {getShowText(message.text)}
                    </div>
                  </div>
                </>
              )}
              {message.type === 'user' && (
                <div className={styles.messages}>{message.text}</div>
              )}
            </div>
          ))}
          {isWaiting && (
            <div className={styles.waitingTip}>
              <LoaderIcon className={styles.animateSpin} />
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>

        <div className={styles.inputArea}>
          <Input
            className={`${styles.input} ${isDarkTheme ? styles.darkInput : ''}`}
            placeholder="请输入提问内容..."
            value={inputText}
            onChange={val => setInputText(val)}
            onEnterPress={handleSend}
            disabled={isLoading}
          />
          <Button
            className={`${styles.sendButton} ${
              isLoading ? styles.disabled : ''
            }`}
            onClick={handleSend}
            disabled={isLoading}
          >
            <LocationOutline />
          </Button>
        </div>
      </div>
    </div>
  );
};
